package com.sl.biz.modular.ai.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.sl.biz.modular.ai.controller.domain.request.AiGenerateEntityRequest;
import com.sl.biz.modular.ai.dao.domain.entity.AiConfigDO;
import com.sl.biz.modular.ai.model.IChatModelService;
import com.sl.biz.modular.ai.service.AiChatRunBizService;
import com.sl.biz.modular.ai.service.AiConfigBizService;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@RequiredArgsConstructor
public class AiChatRunBizServiceImpl implements AiChatRunBizService {
    private final AiConfigBizService aiConfigBizService;

    private final Map<String, IChatModelService> chatModelServiceMap;

    @Override
    public <T> T execute(AiGenerateEntityRequest aiGenerateEntityRequest, Class<T> tClass) {
        String aiCode = aiGenerateEntityRequest.getAiCode();
        AiConfigDO byCode = aiConfigBizService.getByCode(aiCode);
        String keywords = aiGenerateEntityRequest.getKeywords();
        String prefixKeywords = aiGenerateEntityRequest.getPrefixKeywords();

        if (ObjectUtil.isNull(byCode)) {
            return null;
        }

        if (ObjectUtil.equals(byCode.getDisableFlag(), 1)) {
            return null;
        }
        String token = byCode.getToken();
        token=StrUtil.blankToDefault(token,byCode.getApiKey());
        keywords = StrUtil.concat(true, prefixKeywords, ",", keywords);

        IChatModelService iChatModelService = chatModelServiceMap.get(aiCode);
        if (ObjectUtil.isNull(iChatModelService)) {
            return null;
        }
        ChatModel chatModel = iChatModelService.getChatModel(token);

        ChatClient chatClient = ChatClient.create(chatModel);

        T t = chatClient.prompt()
                .user(keywords)
                .call()
                .entity(tClass);
        return t;
    }
}
